import { createRouter, createWebHashHistory } from 'vue-router';
import Login from '../views/Login.vue';
import MainBox from '../views/MainBox.vue';
import RouterConfig from '../router/config';
import Store from '../store/index';

const router_name_login = 'login';
const router_name_mainbox = 'mainbox';

const routes = [
	{
		path: '/login',
		name: router_name_login,
		component: Login,
	},
	{
		path: '/{router_name_mainbox}',
		name: router_name_mainbox,
		component: MainBox,
	},
];

const router = createRouter({
	history: createWebHashHistory(),
	routes,
});

router.beforeEach((to, from, next) => {
	// 登录
	if (to.name == router_name_login) {
		next();
		return;
	}

	// 未登录 or 无权限
	if (!localStorage.getItem('token')) {
		next({ path: '/login' });
		return;
	}

	// 有权限 - 未配置路由
	if (!Store.state.isGetterRouter) {
		_setRouterConfig();
		next({ path: to.fullPath });
		return;
	}

	// 有权限 - 已配置路由
	next();
});

const _setRouterConfig = () => {
	RouterConfig.forEach((item) => {
		router.addRoute(router_name_mainbox, item);
	});

	Store.commit('changeIsGetterRouter', true);

	// RouterConfig.forEach(()=>{
	//   router.removeRoute(router_name_mainbox, item)
	// })
};

export default router;
